package com.quincysx.messager;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * @author QuincySx
 * @date 2018/5/4 上午9:03
 */
public class RemoteService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //返回 Messenger 的 Binder
        return new Messenger(new HandlerMessenger()).getBinder();
    }

    /**
     * 服务端消息处理器
     */
    private class HandlerMessenger extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RemoteContract.SEND_SERVICE_MSG:
                    Bundle data = msg.getData();
                    Log.e("==Service 收到消息==", data.getString(RemoteContract.EXT_MSG));

                    String msgStr = "我在忙等会搭理你";

                    Message message = Message.obtain(null, RemoteContract.SEND_CLIENT_MSG);
                    Bundle bundle = new Bundle();
                    bundle.putString(RemoteContract.EXT_MSG, msgStr);
                    message.setData(bundle);

                    try {
                        Log.e("==Service 发送消息==", msgStr);

                        //获取客户端 Messenger
                        Messenger clientMessenger = msg.replyTo;
                        clientMessenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
            }
        }
    }


}
